package cmd

import (
	"fmt"
	"WorkReport/web"
	"WorkReport/web/model/utils"
	"github.com/spf13/cobra"
	"log"

	//"github.com/spf13/viper"
	"os"
)

//var cfgFile string
var (
	Port string
	Run  bool

	DBUser   string
	DBPwd    string
	DBHost   string
	DBPort   string
	DBName   string
	username string
	password string

	//version info
	version   string
	commitID  string
	buildTime string
	goVersion string
	buildUser string
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "WorkReport",
	Short: "WorkReport 是用于记录工作日志的系统",
	Long:  `WorkReport 是用于记录工作日志的系统`,

	Run: func(cmd *cobra.Command, args []string) {
		cmd.Help()
	},
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		log.Println(err)
		os.Exit(1)
	}
}

func init() {
	//cobra.OnInitialize(initConfig)
	runCmd.Flags().StringVarP(&Port, "port", "P", "8080", "web server listen port.")

	initCmd.Flags().StringVarP(&DBName, "DBName", "d", "worklog", "database name.")
	initCmd.Flags().StringVarP(&DBPwd, "DBPwd", "p", "P@ssw0rd", "database password.")
	initCmd.Flags().StringVarP(&DBUser, "DBUser", "u", "root", "database user.")
	initCmd.Flags().StringVarP(&DBHost, "DBHost", "i", "127.0.0.1", "database host IP.")
	initCmd.Flags().StringVarP(&DBPort, "DBPort", "c", "3306", "database host port.")
	initCmd.Flags().StringVarP(&username, "username", "n", "admin", "login username.")
	initCmd.Flags().StringVarP(&password, "password", "w", "P@ssw0rd", "login user password.")

	rootCmd.AddCommand(versionCmd)
	rootCmd.AddCommand(initCmd)
	rootCmd.AddCommand(runCmd)
}

var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "Print the version number of workLog",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Printf("Version:   %s\n", version)
		fmt.Printf("CommitID:  %s\n", commitID)
		fmt.Printf("BuildTime: %s\n", buildTime)
		fmt.Printf("GoVersion: %s\n", goVersion)
		fmt.Printf("BuildUser: %s\n", buildUser)
	},
}

var initCmd = &cobra.Command{
	Use:   "init",
	Short: "init database.",
	Run: func(cmd *cobra.Command, args []string) {

		if DBName != "" &&DBPwd!=""{
			err:=utils.InitTables(DBUser, DBPwd, DBHost, DBPort, DBName, username, password)
			if err!=nil{
				log.Println(err)
				return
			}
		} else {
			log.Println("please enter DBUser,DBPwd,DBHost,DBPort,DBName.")
			cmd.Help()
		}

	},
}
var runCmd = &cobra.Command{
	Use:   "run",
	Short: "run server.",
	Run: func(cmd *cobra.Command, args []string) {
		utils.InitDB(DBUser, DBPwd, DBHost, DBPort, DBName )
		web.StrartServer(Port)
	},
}
